import sys
sys.path.append("../../")
import fitlog
from transformers import DistilBertConfig
from transformers import DistilBertTokenizer
from transformers import BertTokenizer, BertConfig
from datareader import *
from metrics import *
from model import *
import pickle
from tqdm import trange
import torch
import pdb

class GradientReversal(torch.autograd.Function):
    """
    Basic layer for doing gradient reversal
    """
    lambd = 1.0
    @staticmethod
    def forward(ctx, x):
        return x

    @staticmethod
    def backward(ctx, grad_output):
        return GradientReversal.lambd * grad_output.neg()

def Generator1(labeledSource, unlabeledTarget, labeledTarget, batchSize):
    halfBS = batchSize // 2
    bs2 = halfBS if halfBS < len(labeledTarget) else len(labeledTarget)
    bs1 = batchSize - bs2
    bs3 = batchSize // 3 if batchSize < 3 * len(unlabeledTarget) else len(unlabeledTarget)
    iter1, iter2, iter3 = len(labeledSource) // bs1, \
                          len(labeledTarget) // bs2, \
                          len(unlabeledTarget) // bs3
    maxIters = max([iter1, iter2, iter3])
    def generator():
        idxsS, idxsLT, idxsUT = [], [], []
        for i in range(maxIters + 1):
            if i % iter1 == 0:
                idxsS = random.sample(range(len(labeledSource)), len(labeledSource)) * 2
            if i % iter2 == 0:
                idxsLT = random.sample(range(len(labeledTarget)), len(labeledTarget)) * 2
            if i % iter3 == 0:
                idxsUT = random.sample(range(len(unlabeledTarget)), len(unlabeledTarget)) * 2
            # i * bs1 could be larger than the len(labelSource), thus we need to start from the remainder
            start_LS, start_LT, start_UT = (i * bs1) % len(labeledSource), \
                                           (i * bs2) % len(labeledTarget), \
                                           (i * bs3) % len(unlabeledTarget)
            end_LS, end_LT, end_UT = start_LS + bs1, start_LT + bs2, start_UT + bs3

            items1 = [labeledSource[jj] for jj in idxsS[start_LS:end_LS]]
            items2 = [labeledTarget[jj] for jj in idxsLT[start_LT:end_LT]]
            items3 = [unlabeledTarget[jj] for jj in idxsUT[start_UT:end_UT]]
            batch1 = labeledTarget.collate_raw_batch(items1 + items2)
            batch2 = unlabeledTarget.collate_raw_batch(
                random.sample(items2, batchSize - bs1 - bs3) + items1 + items3
            )
            yield batch1, batch2
    return maxIters, generator

def Generator2(labeledSource, unlabeledTarget, batchSize):
    bs2 = batchSize // 2 if batchSize < 2 * len(unlabeledTarget) else len(unlabeledTarget)
    iter1, iter2 = len(labeledSource) // batchSize, \
                   len(unlabeledTarget) // bs2
    maxIters = max([iter1, iter2])
    def generator():
        idxsS, idxsUT = [], []
        for i in range(maxIters + 1):
            if i % iter1 == 0:
                idxsS = random.sample(range(len(labeledSource)), len(labeledSource)) * 2
            if i % iter2 == 0:
                idxsUT = random.sample(range(len(unlabeledTarget)), len(unlabeledTarget)) * 2
            # i * bs1 could be larger than the len(labelSource), thus we need to start from the remainder
            start_LS, start_UT = (i * batchSize) % len(labeledSource), \
                                    (i * bs2) % len(unlabeledTarget)
            end_LS, end_UT = start_LS + batchSize, start_UT + bs2

            items1 = [labeledSource[jj] for jj in idxsS[start_LS:end_LS]]
            items2 = [unlabeledTarget[jj] for jj in idxsUT[start_UT:end_UT]]
            batch1 = labeledSource.collate_raw_batch(items1)
            batch2 = unlabeledTarget.collate_raw_batch(
                random.sample(items1, batchSize - bs2) + items2
            )
            yield batch1, batch2 # batch1 for CE Loss, batch2 for DA Loss
    return maxIters, generator

def DataIter(labeledSource, unlabeledTarget, labeledTarget=None, batchSize=32):
    if labeledTarget is not None:
        assert len(labeledTarget) > 0
        return  Generator1(labeledSource, unlabeledTarget, labeledTarget, batchSize)
    else:
        return Generator2(labeledSource, unlabeledTarget, batchSize)

class MMEUtils:
    def __init__(self, random_seed):
        self.seed = random_seed

    def initTrainingEnv(self):
        random.seed(self.seed)
        np.random.seed(self.seed)
        torch.manual_seed(self.seed)
        torch.cuda.manual_seed_all(self.seed)
        torch.backends.cudnn.deterministic = True
        torch.backends.cudnn.benchmark = False

    def acc_P_R_F1(self, y_true, y_pred):
        return accuracy_score(y_true, y_pred.cpu()), \
                    precision_recall_fscore_support(y_true, y_pred.cpu())

    def dataIter(self, pseudo_set, labeled_target=None, batch_size=32):
        p_idxs = list(range(len(pseudo_set))) if not hasattr(pseudo_set, 'valid_indexs') else pseudo_set.valid_indexs
        p_len = len(p_idxs)
        if labeled_target is None:
            l_len = 0
            l_idxs = []
        else:
            l_idxs = list(range(len(labeled_target))) if not hasattr(labeled_target, 'valid_indexs') \
                                                        else labeled_target.valid_indexs
            l_len = len(l_idxs)
        data_size = p_len + l_len
        idxs = random.sample(range(data_size), data_size)*2
        for start_i in range(0, data_size, batch_size):
            batch_idxs = idxs[(start_i):(start_i+batch_size)]
            items = [pseudo_set[p_idxs[idx]] if idx < p_len else \
                        labeled_target[l_idxs[idx-p_len]] for idx in batch_idxs]
            yield pseudo_set.collate_raw_batch(items)

    def obtainOptim(self, tr_model, learning_rate):
        return torch.optim.Adam([
            {'params': tr_model.parameters(), 'lr': learning_rate}
        ])

    def Batch2Vecs(self, model: VanillaBert, batch):
        if batch[0].device != model.device:  # data is on a different device
            input_ids, masks, seg_ids = batch[0].to(model.device), \
                                        batch[1].to(model.device), \
                                        batch[2].to(model.device)
        else:
            input_ids, masks, seg_ids = batch[0], batch[1], batch[2]
        encoder_dict = model.bert.bert.forward(
            input_ids=input_ids,
            attention_mask=masks,
            token_type_ids=seg_ids
        )
        return encoder_dict.pooler_output

    def AugBatch2Vecs(self, model:VanillaBert, batch):
        rand = random.random()
        if rand < 0.2:
            model.bert.bert.embeddings.aug_type = "gaussian"
        elif rand < 0.4:
            model.bert.bert.embeddings.aug_type = "g_blur"
        elif rand < 0.6:
            loss, acc = model.RDMLoss(batch)
            loss.backward()
            model.bert.bert.embeddings.aug_type = "adver"
        elif rand < 0.8:
            model.bert.bert.embeddings.aug_type = "rMask"
        else:
            model.bert.bert.embeddings.aug_type = "rReplace"
        return self.Batch2Vecs(model, batch)

    def lossAndAcc(self, model:VanillaBert, batch, temperature=1.0):
        pooledOutput = self.Batch2Vecs(model, batch)
        logits = model.bert.classifier(pooledOutput)
        preds = F.softmax(logits / temperature, dim=1)
        epsilon = torch.ones_like(preds) * 1e-8
        preds = (preds - epsilon).abs()  # to avoid the prediction [1.0, 0.0], which leads to the 'nan' value in log operation
        labels = batch[-2].to(preds.device)
        labels = labels.argmax(dim=1) if labels.dim() == 2 else labels
        loss = F.nll_loss(preds.log(), labels)
        acc = accuracy_score(labels.cpu().numpy(), preds.argmax(dim=1).cpu().numpy())
        return loss, acc

    def dataset_logits(self, model:VanillaBert, data, idxs=None, batch_size=40):
        preds = []
        if idxs is None:
            idxs = list(range(len(data)))
        for i in trange(0, len(idxs), batch_size):
            batch_idxs = idxs[i:min(len(idxs), i + batch_size)]
            batch = data.collate_raw_batch([data[idx] for idx in batch_idxs])
            pred = model.predict(batch, temperature=1.0)
            preds.append(pred)
        pred_tensor = torch.cat(preds)
        return pred_tensor

    def dataset_inference(self, model:VanillaBert, data, idxs=None, batch_size=20):
        pred_tensor = self.dataset_logits(model, data, idxs, batch_size)
        vals, idxs = pred_tensor.sort(dim=1)
        return idxs[:, 1], vals[:, 1]

    def perf(self, model:VanillaBert, data, label, idxs=None, batch_size=20):
        with torch.no_grad():
            predTensor = self.dataset_logits(model, data, idxs, batch_size)
            _, yPred = predTensor.sort(dim=1)
        label = label if label.dim() == 1 else label.argmax(dim=1)
        yTrue = label[idxs] if idxs is not None else label
        loss = F.nll_loss(predTensor.log(), yTrue.to(predTensor.device))
        return self.acc_P_R_F1(yTrue, yPred[:, -1]) + (loss,)

class MMETrainer(MMEUtils):
    def __init__(self, seed, log_dir, suffix, model_file, class_num, temperature=1.0,
                 learning_rate=5e-3, batch_size=32, Lambda=0.1):
        super(MMETrainer, self).__init__(seed)
        if not os.path.exists(log_dir):
            os.system("mkdir %s" % log_dir)
        else:
            os.system("rm -rf %s" % log_dir)
            os.system("mkdir %s" % log_dir)
        fitlog.set_log_dir(log_dir, new_log=True)
        self.log_dir = log_dir
        self.suffix = suffix
        self.model_file = model_file
        self.best_valid_acc = 0.0
        self.min_valid_loss = 1e8
        self.class_num = class_num
        self.temperature = temperature
        self.learning_rate = learning_rate
        self.batch_size = batch_size
        self.Lambda = Lambda
        self.valid_step = 0

    def Entrophy(self, trModel: VanillaBert, batch):
        if batch[0].device != trModel.device:  # data is on a different device
            inputIds, masks, segIds = batch[0].to(trModel.device), \
                                      batch[1].to(trModel.device), \
                                      batch[2].to(trModel.device)
        else:
            inputIds, masks, segIds = batch[0], batch[1], batch[2]
        pooledOutput = trModel.PoolerVecs(inputIds, token_ids=segIds, attention_mask=masks)
        pooledOutput = trModel.bert.dropout(pooledOutput)
        pooledOutput = GradientReversal.apply(pooledOutput)
        normedPoolOut = pooledOutput / (pooledOutput.norm())
        logits = trModel.bert.classifier(normedPoolOut)
        preds = F.softmax(logits / self.temperature, dim=1)
        epsilon = torch.ones_like(preds) * (1e-8)
        preds = (preds - epsilon).abs()
        loss = -1 * (preds * (preds.log())).sum()
        return loss

    def ModelTrain(self, trModel: VanillaBert, labeled_source: NLIDataset, labeled_target: NLIDataset,
                   unlabeled_target: NLIDataset, valid_target: NLIDataset, UT_Label, maxEpoch, validEvery=20):
        self.initTrainingEnv()
        optimizerGroupedParameters = [
            {'params': p,
             'lr': self.learning_rate * pow(0.8, 12 - int(n.split("layer.")[1].split(".", 1)[0])) if "layer." in n \
                 else (self.learning_rate * pow(0.8, 13) if "embedding" in n else self.learning_rate)
             # layer-wise fine-tuning
             } for n, p in trModel.named_parameters()
        ]
        optim = torch.optim.Adam(optimizerGroupedParameters)
        bestAcc = 0.0
        for epoch in range(maxEpoch):
            maxIters, trainLoader = DataIter(labeled_source, unlabeled_target, labeled_target, self.batch_size)
            for step, (batch1, batch2) in enumerate(trainLoader()):
                loss, acc = trModel.lossAndAcc(batch1, temperature=self.temperature)
                HEntrophy = self.Entrophy(trModel, batch2)
                trainLoss = loss - self.Lambda * HEntrophy
                optim.zero_grad()
                trainLoss.backward()
                optim.step()
                torch.cuda.empty_cache()
                print('####Model Update (%3d | %3d) %3d | %3d ####, loss = %6.8f, entrophy = %6.8f' % (
                    step, maxIters, epoch, maxEpoch, loss, HEntrophy.data.item()
                ))
                if (step + 1) % validEvery == 0:
                    rst = self.perf(trModel, valid_target, valid_target.labelTensor())
                    acc_v, (p_v, r_v, f1_v, _), loss_v = rst
                    print("valid perf:", rst)
                    output_items = [("valid_acc", acc_v)] + \
                                   [("valid_loss", loss_v)] + \
                                   [('valid_prec_{}'.format(i), p_v[i]) for i in range(self.class_num)] + \
                                   [('valid_recall_{}'.format(i), r_v[i]) for i in range(self.class_num)] + \
                                   [('valid_f1_{}'.format(i), f1_v[i]) for i in range(self.class_num)]
                    fitlog.add_metric({f"ValidPerf_{self.suffix}": dict(output_items)}, step=self.valid_step)
                    self.logPerf(trModel, unlabeled_target, UT_Label, self.suffix)

                    if acc_v > bestAcc:
                        torch.save(trModel.state_dict(), self.model_file)
                        bestAcc = acc_v

    def ModelTrainV2(self, trModel: VanillaBert, labeled_source: NLIDataset, labeled_target: NLIDataset,
                        unlabeled_target: NLIDataset, valid_target: NLIDataset, UT_Label, maxEpoch,
                            validEvery=20, E_Step=1, T_Step=5):
        self.initTrainingEnv()
        optimizerGroupedParameters = [
            {'params': p,
             'lr': self.learning_rate * pow(0.8, 12 - int(n.split("layer.")[1].split(".", 1)[0])) if "layer." in n \
                 else (self.learning_rate * pow(0.8, 13) if "embedding" in n else self.learning_rate)
             # layer-wise fine-tuning
             } for n, p in trModel.named_parameters()
        ]
        optim = torch.optim.Adam(optimizerGroupedParameters)
        bestAcc = 0.0
        for epoch in range(maxEpoch):
            maxIters, trainLoader = DataIter(labeled_source, unlabeled_target, labeled_target, self.batch_size)
            for step, (batch1, batch2) in enumerate(trainLoader()):
                try:
                    for da_idx in range(E_Step):
                        HEntrophy = self.Entrophy(trModel, batch2)
                        optim.zero_grad()
                        (-1.0 * self.Lambda * HEntrophy).backward()
                        optim.step()
                        print('####Domain Adversarial [%3d] (%3d | %3d) %3d | %3d #### T_Entrophy = %6.8f' % (
                            da_idx, step, maxIters, epoch, maxEpoch, HEntrophy.data.item()
                        ))

                    for td_idx in range(T_Step):
                        loss, acc = self.lossAndAcc(trModel, batch1, self.temperature)
                        optim.zero_grad()
                        loss.backward()
                        optim.step()
                        print('****Task Discriminative [%3d] (%3d | %3d) %3d | %3d **** Loss/Acc = %6.8f/%6.8f' % (
                            td_idx, step, maxIters, epoch, maxEpoch, loss.data.item(), acc
                        ))
                except:
                    print("batch1 input shape : ", batch1[0].shape)
                    print("batch2 input shape : ", batch2[0].shape)
                    print("batch 1 : \n", batch1)
                    print("batch 2 : \n", batch2)
                    raise

                if (step + 1) % validEvery == 0:
                    rst = self.perf(trModel, valid_target, valid_target.labelTensor())
                    acc_v, (p_v, r_v, f1_v, _), loss_v = rst
                    print("valid perf:", rst)
                    output_items = [("valid_acc", acc_v)] + \
                                   [("valid_loss", loss_v)] + \
                                   [('valid_prec_{}'.format(i), p_v[i]) for i in range(self.class_num)] + \
                                   [('valid_recall_{}'.format(i), r_v[i]) for i in range(self.class_num)] + \
                                   [('valid_f1_{}'.format(i), f1_v[i]) for i in range(self.class_num)]
                    fitlog.add_metric({f"ValidPerf_{self.suffix}": dict(output_items)}, step=self.valid_step)
                    self.logPerf(trModel, unlabeled_target, UT_Label, self.suffix)
                    if acc_v > bestAcc:
                        torch.save(trModel.state_dict(), self.model_file)
                        bestAcc = acc_v

    def logPerf(self, model, test_set, test_label, test_suffix, step=0):
        rst_model = self.perf(model, test_set, test_label)
        print("BestPerf : ", rst_model)
        acc_v, (p_v, r_v, f1_v, _), loss_v = rst_model
        output_items = [("test_acc", acc_v)] + \
                       [("test_loss", loss_v)] + \
                       [('test_prec_{}'.format(i), p_v[i]) for i in range(self.class_num)] + \
                       [('test_recall_{}'.format(i), r_v[i]) for i in range(self.class_num)] + \
                       [('test_f1_{}'.format(i), f1_v[i]) for i in range(self.class_num)]
        fitlog.add_metric({f"BestPerf_{test_suffix}": dict(output_items)}, step=self.valid_step)
        self.valid_step += 1

def obtain_model(args, model_device):
    bert_model = 'bert-base-uncased' if args.full_bert else 'distilbert-base-uncased'
    if args.full_bert:
        bert_config = BertConfig.from_pretrained(bert_model, num_labels=2) if args.bertPath is None else \
                        BertConfig.from_pretrained(args.bertPath, num_labels=2)
        tokenizer_M = BertTokenizer.from_pretrained(bert_model) if args.bertPath is None else \
                        BertTokenizer.from_pretrained(args.bertPath)
    else:
        bert_config = DistilBertConfig.from_pretrained(bert_model, num_labels=2) if args.distillBertPath is None else \
                        DistilBertConfig.from_pretrained(args.distillBertPath, num_labels=2)
        tokenizer_M = DistilBertTokenizer.from_pretrained(bert_model) if args.distillBertPath is None else \
                        DistilBertTokenizer.from_pretrained(args.distillBertPath)
    bert_config.num_labels = 3
    bert_config.hidden_act = "relu"
    # Create the model
    if args.full_bert:
        bert = BertForSequenceClassification.from_pretrained(
                        bert_model, config=bert_config).to(model_device) if args.bertPath is None \
                else BertForSequenceClassification.from_pretrained(
                        args.bertPath, config=bert_config).to(model_device)
    else:
        bert = DistilBertForSequenceClassification.from_pretrained(
                    bert_model, config=bert_config).to(model_device) if args.distillBertPath is None \
                else DistilBertForSequenceClassification.from_pretrained(
                        args.distillBertPath, config=bert_config).to(model_device)
    model = VanillaBert(bert).to(model_device)
    return model, tokenizer_M

def obtain_domain_set(new_domain_name, tokenizer_M, lt_count=0):
    SNLI_set = NLIDataset("../../../snli_1.0/snli_1.0_train.jsonl", tokenizer=tokenizer_M)
    testFile = f"../../../multinli_1.0/Domain_{new_domain_name}.jsonl"
    if lt_count != 0:
        filenames = SplitDataFile(testFile, accumulation=[lt_count, -1])
        labeled_target = NLIDataset(filenames[0], tokenizer=tokenizer_M)
        test_set = NLIDataset(filenames[1], tokenizer=tokenizer_M)
    else:
        labeled_target = None
        test_set = NLIDataset(testFile, tokenizer=tokenizer_M)
    val_set = NLIDataset(f"../../../multinli_1.0/fewshot_Domain_{new_domain_name}.jsonl",
                              tokenizer=tokenizer_M, max_data_size=100)
    return SNLI_set, val_set, test_set, labeled_target

def SplitDataFile(fname, accumulation=[0, -1]):
    with open(fname, 'r') as fr:
        lines = [line for line in fr]
    lines = random.sample(lines, len(lines))

    accumulation[-1] = len(lines)
    s = fname.rsplit(".", 1)
    start = 0
    out_file_list = []
    for i, end in enumerate(accumulation):
        sub_file = f"{s[0]}_{i}.{s[1]}"
        with open(sub_file, 'w') as fw:
            fw.write("".join(lines[start:end]))
        out_file_list.append(sub_file)
        start = end
    return out_file_list

def reconfig_args(args):
    args.full_bert = True
    args.bertPath = "../../../bert_en/"

    args.full_bert = True
    print("====>", args.full_bert)
    return args

if __name__ == "__main__":
    with open("../../args.pkl", 'rb') as fr:
        argConfig = pickle.load(fr)
    argConfig.model_dir = str(__file__).rstrip(".py")
    # Set all the seeds
    seed = argConfig.seed
    reconfig_args(argConfig)

    # See if CUDA available
    device = torch.device("cpu") if not torch.cuda.is_available() else torch.device("cuda:0")
    model1_path = "../../saved/modelSNLI_1.pth"

    domainID = 2
    fewShotCnt = 100
    NLIDomainList = list(NLI_domain_map.keys())
    newDomainName = NLIDomainList[domainID-1]

    model1, tokenizer = obtain_model(args=argConfig, model_device=device)
    tokenizer.model_max_length = 128
    labeledSource, validTarget, unlabeledTarget, labeledTarget = obtain_domain_set(newDomainName,
                                                                                   tokenizer_M=tokenizer,
                                                                                   lt_count=0)
    model1.load_state_dict(torch.load(model1_path))
    trainer = MMETrainer(seed=seed, log_dir=argConfig.model_dir, suffix=f"{newDomainName}_FS{fewShotCnt}",
                         model_file=f"{argConfig.model_dir}/MME_{newDomainName}_FS{fewShotCnt}",
                         class_num=3, temperature=0.05, learning_rate=2e-5, batch_size=20,
                         Lambda=0.1)
    trainer.ModelTrainV2(model1, labeledSource, labeledTarget, unlabeledTarget, validTarget,
                       UT_Label=unlabeledTarget.labelTensor().clone(), maxEpoch=10, validEvery=20)
